<?php
require 'TVB/pms/pdes/common/bootstrap.php';

$query  =	empty($_REQUEST['q'])	?	''	:	$_REQUEST['q'];
$type	=	empty($_REQUEST['type']) ?	''	:	$_REQUEST['type'];

$query_string = '';
$field_array  = array('title'=>'concat(en.title," ",cn.title)', 'path'=>'p.path','id'=>'p.id');

if(isset($field_array[$type])){
	if('id' == $type){
		$query = (int)$query;
		$query_string = 'p.id=:query';
	}else{
		$query = "%$query%";
		$query_string = $field_array[$type].' LIKE :query';
	}
}else{
	exit('[]');
}

$sql = '
	SELECT p.id, p.path, CONCAT(IFNULL(en.title,""), " ", IFNULL(cn.title,"")) AS title, "'.$type.'" AS "type" 
	FROM programme AS p LEFT JOIN 
		(SELECT programme_id,title FROM `programme-language` AS pl_en WHERE pl_en.language_id=:en) AS en ON p.id=en.programme_id LEFT JOIN
		(SELECT programme_id,title FROM `programme-language` AS pl_en where pl_en.language_id=:cn) AS cn ON p.id=cn.programme_id 
	WHERE '.$query_string.' LIMIT 20';

$params = array(
	':en'=>language::getLanguageID(AC::LANGUAGE_EN),
	':cn'=>language::getLanguageID(AC::LANGUAGE_ZH),
	':query'=>$query
);

if(isset($_REQUEST['unpublish']) && $_REQUEST['unpublish']){
	$dbo    = CommonUtils::getDbConn(0,'preview')->getDbHandle();
	$result = CommonUtils::exec_sql($dbo,$sql,$params);
}else{
	$result	= Model::selectBySql($sql,$params);
}

echo json_encode($result);

